﻿using DongFangGuoKai.WMS.IApiService;
using DongFangGuoKai.WMSPlatform.Domain.AGVModels;
using DongFangGuoKai.WMSPlatform.Domain.Enums;
using DongFangGuoKai.WMSPlatform.Domain.Model;
using DongFangGuoKai.WMSPlatform.Domain.Models;
using DongFangGuoKai.WMSPlatform.Domain.WCSModels;
using Microsoft.Extensions.Logging;
using SqlSugar;

namespace DongFangGuoKai.WMS.NodeBussiness
{
    /// <summary>
    /// 空箱入货架
    /// </summary>
    public class PDAEmptyContainerBusiness : NodeBaseBusiness
    {
        private readonly ISqlSugarClient _sugarClient;
        private readonly IAGVService _agvApiService;
        private readonly ILogger<PDAEmptyContainerBusiness> _logger;

        public PDAEmptyContainerBusiness(IServiceProvider provider, ISqlSugarClient sugarClient, IAGVService agvApiService, ILogger<PDAEmptyContainerBusiness> logger) : base(provider)
        {
            DeviceAction = EmDeviceAction.Transport;
            WorkDeviceType = EmWorkDeviceType.AGV;
            InstructType = EmInstructType.Move;

            _sugarClient = sugarClient;
            _agvApiService = agvApiService;
            _logger = logger;
        }
        protected override bool ExecCreateInstruct(out string msg, params object[] data)
        {
            msg = string.Empty;
            bool flag = false;

            var model = data[0] as ConveyorLineContainerModel;
            if (model == null)
            {
                msg = "参数错误";
                return false;
            }
            lock (_lockObj)
            {
                var pallnet = _sugarClient.Queryable<t_Pallet>().First(t => t.PalletBarcode == model.PalletBarcode);
                if (pallnet == null)
                {
                    msg = $"{model.PalletBarcode}托盘不存在";
                    return false;
                }
                if (pallnet.Status == 0)
                {
                    msg = $"{model.PalletBarcode}托盘已禁用";
                    return false;

                }
                if (!string.IsNullOrEmpty(pallnet.LocationCode))
                {
                    msg = $"{model.PalletBarcode}托盘已在储位：{pallnet.LocationName}";
                    return false;

                }
                var instructPallet = _sugarClient.Queryable<t_Instruct>().Where(t => t.PalletBarcode == pallnet.PalletBarcode).OrderByDescending(o => o.Id).First();
                if (instructPallet != null)
                {
                    if (instructPallet.Status <= 2)
                    {
                        msg = $"{pallnet.LocationName} 任务已在执行";
                        return false;
                    }
                }

                string logicPartCode = pallnet.LogicalPartCode;
                string palletBarcode = pallnet.PalletBarcode;
                //分拨仓位
                var allocateCell = _sugarClient.Queryable<t_Cell>().Where(t => t.LogicalPartCode == "DistributionArea" && t.IsLock == false && t.BusinessType == 0 && t.Status == 1 && t.FullStatus == 0 && t.ColumnNO <= 20)
                    .OrderBy(o => o.LineNO)
                    .OrderBy(o => o.ColumnNO)
                    .OrderBy(o => o.LayerNO)
                    .First();
                if (allocateCell == null)
                {
                    //"SELECT TOP 1 * from  t_Cell WHERE LogicalPartCode={0} and IsLock={1} and Status={2}  and  BusinessType={3} and FullStatus={4} ORDER BY [LineNO] ASC,[LayerNO] ASC,[ColumnNO] ASC", pallnet.LogicalPartCode, "0", "1", "0", "0"
                    //List<int> ints = new List<int>()
                    // {
                    //     8,9
                    // };
                    //allocateCell = _sugarClient.Queryable<t_Cell>().Where(t => ints.Contains(t.ShelfId) && t.LayerNO == 4 && t.IsLock == false && t.Status == 1 && t.BusinessType == 0 && t.FullStatus == 0)
                    //.OrderBy(o => o.LineNO)
                    //.OrderBy(o => o.ColumnNO)
                    //.OrderBy(o => o.LayerNO)

                    //.First();
                }
                if (allocateCell == null)
                {
                    msg = "无可用仓位";
                    return false;
                }

                var newPallet = _sugarClient.Queryable<t_Pallet>().Where(t => t.LocationCode == allocateCell.Code).First();
                if (newPallet != null)
                {
                    msg = $" {allocateCell.Name}：{newPallet.PalletName}已存在托盘";
                    return false;
                }
                _sugarClient.Ado.BeginTran();
                try
                {

                    allocateCell.Status = 2;//锁定 
                    allocateCell.FullStatus = 0; //空箱
                    allocateCell.BusinessType = EmBusinessType.Move;  //入库  

                    flag = _sugarClient.Updateable(allocateCell)
                        .UpdateColumns("Status", "FullStatus", "BusinessType")
                        .ExecuteCommand() > 0;
                    if (!flag)
                    {
                        _sugarClient.Ado.RollbackTran();
                        msg = "修改仓位失败";
                        return false;
                    }

                    Guid guid = Guid.NewGuid();
                    t_Instruct instruct = new t_Instruct()
                    {
                        BusinessGroupId = guid,
                        CreateUserId = 1,
                        CreateUserName = "admin",
                        Status = 2,
                        Action = EmDeviceAction.Transport,
                        WorkDeviceType = EmWorkDeviceType.AGV,
                        InstructType = EmInstructType.Move,
                        ExpectedToLocation = allocateCell.Code,//目标地址
                        FromLocation = "S00001S1502013",   //源地址
                        InstructIndex = 1,
                        PalletBarcode = palletBarcode,
                        ScanedBarcode = palletBarcode,
                        Priority = 9999,
                        FinishedQTY = 0,
                        LogicalCellAddr = allocateCell.ERPCode,
                        StartTime = DateTime.Now,
                    };
                    flag = flag = _sugarClient.Insertable(instruct).ExecuteCommand() > 0;

                    if (!flag)
                    {
                        msg = "指令保存失败";
                        _sugarClient.Ado.RollbackTran();
                        return false;
                    }
                    string ctnrType = "";
                    if (pallnet.Type == 1)
                    {
                        ctnrType = "2";
                    }
                    else if (pallnet.Type == 2)
                    {
                        ctnrType = "1";
                    }
                    //添加任务单
                    AddTaskModel taskModel = new AddTaskModel();

                    //生成32位uuid
                    taskModel.reqCode = guid.ToString("N");
                    taskModel.clientCode = "PDA";
                    //大料箱任务类型
                    taskModel.TaskTyp = "A13";


                    taskModel.CtnrTyp = ctnrType;
                    //生成36位uuid
                    taskModel.taskCode = guid.ToString();

                    //任务起始点仓位编码
                    taskModel.PositionCodePath = new PositionCodePathDto[2] {
                    new PositionCodePathDto() {
                        PositionCode="S00001S1502013",// 起始地址 D00080A2502013
                        Type="05"
                    },
                    new PositionCodePathDto() {
                        PositionCode=allocateCell.ERPCode,//ERP目标地址
                        Type="05"
                    }
                };
                    var res = _agvApiService.CreateTask(taskModel);
                    if (res.code == "1")
                    {
                        _sugarClient.Ado.RollbackTran();
                        msg = $"仓位：{allocateCell.Name} AGV调用失败：" + res.message;
                        return false;
                    }
                    msg = allocateCell.AreaName + ":" + allocateCell.Name;
                    _sugarClient.Ado.CommitTran();
                    return true;

                }
                catch (Exception ex)
                {
                    _sugarClient.Ado.RollbackTran();
                    _logger.LogError(ex.Message);
                    msg = "异常：" + ex.Message;
                    return false;
                }


            }
        }

        protected override bool ExecInstructFinished(TInstruct instruct, out string msg)
        {
            msg = string.Empty;
            bool flag = false;

            string expectedToLocation = instruct.ExpectedToLocation;
            string palletBarcode = instruct.PalletBarcode;

            _sugarClient.Ado.BeginTran();
            try
            {
                var lockCell = _sugarClient.Queryable<t_Cell>().Where(t => t.Code == expectedToLocation).First();
                if (lockCell == null)
                {
                    _sugarClient.Ado.RollbackTran();
                    msg = "仓位不存在";
                    return false;
                }
                var pallet = _sugarClient.Queryable<t_Pallet>().Where(t => t.PalletBarcode == palletBarcode).First();
                if (pallet == null)
                {
                    _sugarClient.Ado.RollbackTran();
                    msg = "托盘不存在";
                    return false;
                }

                pallet.LocationCode = lockCell.Code;
                pallet.LocationName = lockCell.Name;
                pallet.ERPLocationName = lockCell.ERPCode;
                pallet.WarehouseId = lockCell.WhId;
                pallet.WarehouseCode = lockCell.WhCode;
                pallet.WarehouseName = lockCell.WhName;

                flag = _sugarClient.Updateable(pallet).ExecuteCommand() > 0;
                if (!flag)
                {
                    _sugarClient.Ado.RollbackTran();
                    msg = "修改托盘失败";
                    return false;
                }
                lockCell.Status = 8; //空箱
                lockCell.BusinessType = EmBusinessType.None;  //入库  
                flag = _sugarClient.Updateable(lockCell).UpdateColumns("Status", "BusinessType").ExecuteCommand() > 0;
                if (!flag)
                {
                    _sugarClient.Ado.RollbackTran();
                    msg = "修改仓位失败";
                    return false;
                }

                instruct.Status = 3;
                flag = _sugarClient.Updateable(instruct).AS("t_instruct").WhereColumns("Id").UpdateColumns("Status").ExecuteCommand() > 0;
                if (!flag)
                {
                    _sugarClient.Ado.RollbackTran();
                    msg = "修改指令失败";
                    return false;
                }

                _sugarClient.Ado.CommitTran();

                return true;
            }
            catch (Exception ex)
            {
                _sugarClient.Ado.RollbackTran();
                _logger.LogError(ex.Message);
                msg = ex.Message;
                return false;
            }

        }
    }
}
